Page({
  data: {
    questions: [],
    currentQuestion: {},
    currentIndex: 0,
    ageGroup: '',
    isDeep: false,
    total: 0
  },
  onLoad(options) {
    const questionBank = require('../../utils/questionBank');
    const questions = questionBank.questions[options.ageGroup] || [];  // 确认引用
    this.setData({
      questions: questions.map(q => ({
        ...q,
        formattedSource: `来源：${q.source.split(' (')[0]}\n(${q.source.split(' (')[1]?.replace(')', '') || ''})\n(${q.source.split(' (')[2] || ''})`  // 修复分行
      })),
      ageGroup: options.ageGroup,
      isDeep: options.mode === 'deep',
      total: options.mode === 'deep' ? 50 : 20
    });
    this.loadCurrentQuestion();
  },
  loadCurrentQuestion() {
    const q = this.data.questions[this.data.currentIndex];
    this.setData({
      currentQuestion: q ? { ...q, source: q.formattedSource } : {}  // 修复显示
    });
  },
  onAnswerChange(e) {
    this.data.questions[this.data.currentIndex].answer = e.detail.value;
    this.nextQuestion();
  },
  nextQuestion() {
    this.data.currentIndex++;
    if (this.data.currentIndex < this.data.total) {
      this.loadCurrentQuestion();
    } else {
      this.toResult();
    }
  },
  toResult() {
    const score = this.data.questions.slice(0, this.data.total).reduce((s, q) => s + parseInt(q.answer || 1), 0);
    const percent = (score / (this.data.total * 2)) * 100;
    const reportData = {
      ageGroup: this.data.ageGroup,
      isDeep: this.data.isDeep,
      score,
      total: this.data.total * 2,
      interp: `宝宝活力${Math.round(percent)}%，改善可增20%！`
    };
    getApp().globalData.lastReport = reportData;
    wx.setStorageSync('lastReport', reportData);
    const encoded = encodeURIComponent(JSON.stringify(reportData));
    wx.navigateTo({ url: `/pages/result/result?data=${encoded}` });
  }
});